package com.helloandroid.paso.ui.mediaplayer;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.text.TextUtils;

public class M3UParser {
	
	public static ArrayList<Track> parse(String playlist){	
		if(TextUtils.isEmpty(playlist))
			return null;		
		
		ArrayList<Track> temp = new ArrayList<Track>();
		
		// Check if the playlist is extended
		if(playlist.startsWith("#EXTM3U")){
			try {
				// If it is extended parse it with a regex and store relevant information in backreferences
				// Group 1 - Artist/Title, usually separated with a dash
				// Group 2 - Path
				Pattern regex = Pattern.compile("^#EXTINF:[\\d-]+,(.*)\r?\n(.+)", Pattern.MULTILINE);
				Matcher regexMatcher = regex.matcher(playlist);
				
				while (regexMatcher.find()) {
					ID3Tag tag = new ID3Tag();
					
					if(!TextUtils.isEmpty(regexMatcher.group(1))){
					
						int firstDash = regexMatcher.group(1).indexOf("-");
						
						if(firstDash > -1){
							tag.Artist = regexMatcher.group(1).substring(0, firstDash);
						}
						
						tag.Title = regexMatcher.group(1).substring(firstDash + 1);
					}
						
					temp.add(new Track(tag, regexMatcher.group(2)));
				} 
			} catch (PatternSyntaxException ex) {
				return null;
			}
		}
		else{
			try {
				// If it is not extended simply read every line and store them in backreferences
				// Group 1 - Path
				Pattern regex = Pattern.compile("^(.+)", Pattern.MULTILINE);
				Matcher regeMatcher = regex.matcher(playlist);
				
				while(regeMatcher.find()){
					temp.add(new Track(null, regeMatcher.group(1)));
				}
			} catch (PatternSyntaxException e) {
				return null;
			}
		}
		
		return temp;
	}

}
